import { Injectable, NgZone, ApplicationRef, ComponentFactoryResolver, Injector, EmbeddedViewRef, ComponentRef } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { ToastConfig, ToastItem, ToastOptions } from './toast.model';
import { CheeseToastComponent } from './toast.component';

@Injectable({
  providedIn: 'root'
})
export class CheeseToastService {
  private toastList: ToastItem[] = [];
  private toastSubject = new BehaviorSubject<ToastItem[]>([]);
  private defaultOptions: ToastOptions = {
    duration: 3000,
    closable: false,
    position: 'top-center',
    maxCount: 5
  };
  private options: ToastOptions;
  private containerComponentRef: ComponentRef<CheeseToastComponent> | null = null;

  constructor(
    private zone: NgZone,
    private appRef: ApplicationRef,
    private componentFactoryResolver: ComponentFactoryResolver,
    private injector: Injector
  ) {
    this.options = { ...this.defaultOptions };
  }

  // 获取toast列表的Observable
  get toasts$(): Observable<ToastItem[]> {
    return this.toastSubject.asObservable();
  }

  // 设置全局配置
  setConfig(options: ToastOptions): void {
    this.options = { ...this.defaultOptions, ...options };
  }

  // 显示成功提示
  success(message: string, config?: Partial<ToastConfig>): void {
    this.show({ message, type: 'success', ...config });
  }

  // 显示错误提示
  error(message: string, config?: Partial<ToastConfig>): void {
    this.show({ message, type: 'error', ...config });
  }

  // 显示信息提示
  info(message: string, config?: Partial<ToastConfig>): void {
    this.show({ message, type: 'info', ...config });
  }

  // 显示警告提示
  warning(message: string, config?: Partial<ToastConfig>): void {
    this.show({ message, type: 'warning', ...config });
  }

  // 显示提示
  show(config: ToastConfig): void {
    this.zone.run(() => {
      // 确保容器组件已创建
      this.ensureContainerCreated();

      const toast: ToastItem = {
        id: this.generateId(),
        message: config.message,
        type: config.type || 'info',
        duration: config.duration || this.options.duration,
        closable: config.closable !== undefined ? config.closable : this.options.closable,
        position: config.position || this.options.position
      };

      // 限制最大显示数量
      if (this.toastList.length >= (this.options.maxCount || 5)) {
        this.toastList.shift();
      }

      this.toastList.push(toast);
      this.toastSubject.next([...this.toastList]);

      // 设置自动关闭
      if (toast.duration && toast.duration > 0) {
        setTimeout(() => this.remove(toast.id), toast.duration);
      }
    });
  }

  // 移除指定的toast
  remove(id: string): void {
    this.zone.run(() => {
      this.toastList = this.toastList.filter(toast => toast.id !== id);
      this.toastSubject.next([...this.toastList]);
    });
  }

  // 清除所有toast
  clear(): void {
    this.zone.run(() => {
      this.toastList = [];
      this.toastSubject.next([]);
    });
  }

  // 生成唯一ID
  private generateId(): string {
    return `toast-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
  }

  // 确保容器组件已创建
  private ensureContainerCreated(): void {
    if (!this.containerComponentRef) {
      // 创建容器组件
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory(CheeseToastComponent);
      this.containerComponentRef = componentFactory.create(this.injector);
      
      // 附加到应用
      this.appRef.attachView(this.containerComponentRef.hostView);
      
      // 获取DOM元素
      const domElem = (this.containerComponentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
      
      // 添加到body
      document.body.appendChild(domElem);
    }
  }
}